<?php

namespace common\helpers;

use Yii;

class WxInfoHelper
{
    /**
     * 获取用户信息
     *
     * =======================获取用户信息=========================
     * {
     * "openid":  用户的唯一标识openid
     * " nickname": 用户昵称
     * "sex": 用户性别：1=》男，2=》女，0=》未知
     * "province":  省
     * "city":  城市
     * "country":  国家
     * "headimgurl":  用户头像地址
     * "privilege":   用户特权信息
     * "unionid": 只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。
     * }
     * ==========================OVER===========================
     * @param $code
     * @return mixed
     * @author chenyuebin
     */
    public static function getWxInfo($code)
    {
        $accessToken = self::getAccessToken($code);
        if (isset($accessToken['openid'])) {
            $userInfoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $accessToken['access_token'] . '&openid=' . $accessToken['openid'] . '&lang=zh_CN';
            $ret = json_decode(CommonHelper::https_request($userInfoUrl), true);
            $ret['refresh_token'] = $accessToken['refresh_token'];
        } else {
            return $accessToken;
        }
        return $ret;
    }

    /**
     * 获取微信access_token
     *
     * ==========================返回参数===================
     * {
     * "access_token":"ACCESS_TOKEN", token值
     * "expires_in":7200,  过期时间（秒）
     * "refresh_token":"REFRESH_TOKEN",  （刷新token参数，为刷新token时必须参数）
     * "openid":"OPENID",  用户openid
     * "scope":"SCOPE"  作用域，分为：基础授权（静默授权）snsapi_base和snsapi_userinfo
     * }
     * ==========================OVER=====================
     * @param $code
     * @return bool|string
     * @author chenyuebin
     */
    public static function getAccessToken($code)
    {
        $tokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . Yii::$app->params['APPID'] . '&secret=' . Yii::$app->params['APPSECRET'] . '&code=' . $code . '&grant_type=authorization_code';
        return json_decode(CommonHelper::https_request($tokenUrl), true);
    }

    /**
     * 刷新微信access_token
     *
     * ==========================返回参数===================
     * {
     * "access_token":"ACCESS_TOKEN", token值
     * "expires_in":7200,  过期时间（秒）
     * "refresh_token":"REFRESH_TOKEN",  （刷新token参数，为刷新token时必须参数）
     * "openid":"OPENID",  用户openid
     * "scope":"SCOPE"  作用域，分为：基础授权（静默授权）snsapi_base和snsapi_userinfo
     * }
     * ==========================OVER=====================
     * @param $refreshToken
     * @return bool|string
     * @author chenyuebin
     */
    public static function refreshToken($refreshToken)
    {
        $refreshTokenUrl = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . Yii::$app->params['APPID'] . '&grant_type=refresh_token&refresh_token=' . $refreshToken;
        return json_decode(CommonHelper::https_request($refreshTokenUrl), true);
    }

}